/**
 * Copyright 2006-2015 handu.com
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.iepacj.nio.channel;

import com.iepacj.concurrency.ch4.one.SleepUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author amssy
 * @version V1.0
 * @description TODO
 * @date 2016/8/27
 */

public class SocketChannelTest {

    private static final String HELLO = "hello, i must be going!\r";


    public static void main(String[] args) throws IOException {

        testBlock();

    }

    private static void testBlock() throws IOException {

        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        System.out.println("通道是否是阻塞模式: " + serverChannel.isBlocking());

        // 设置通道为非阻塞 true: 阻塞
        serverChannel.configureBlocking(false);

        System.out.println("通道是否是阻塞模式: " + serverChannel.isBlocking());


        serverChannel.bind(new InetSocketAddress("192.168.53.9", 6666));

        /**
         * 非阻塞的ServerSocketChannel在调用accept()方法后会立即返回null
         * 正是这种检查连接而不阻塞的能力实现了可伸缩性并降低了复杂性, 可选择性也因此得到实现
         *
         */
        // SocketChannel sc = serverChannel.accept();
        // System.out.println("有客户端连接: " + sc); // 立即返回null

        // 这样会阻塞
        // serverChannel.socket().accept();

        ByteBuffer buf = ByteBuffer.wrap(HELLO.getBytes());

        while (true) {
            SocketChannel sc = serverChannel.accept();
            if (sc == null) {
                System.out.println("no client, i will sleep for 2s.");
                SleepUtils.second(2);
            }
            if (sc != null) {
                System.out.println("incoming client from: " + sc.getRemoteAddress());
                buf.rewind();
                sc.write(buf);
            }
        }
    }
}
